<?php

namespace app\common\model;

use think\model\concern\SoftDelete;
use think\Validate;

/**
 * User: Feng
 * Date: 2024/05/28
 */
class Scenario extends Common
{
	use SoftDelete;
	//时间自动存储
	protected $autoWriteTimestamp = true;
	protected $createTime = 'ctime';
	protected $updateTime = 'utime';
	//软删除位
	protected $deleteTime = 'isdel';
	//验证规则
	protected $rule = [
		'title' => 'require|max:200'
	];
	protected $msg = [
		'title.require' => '方案标题必须填写',
		'title.max'     => '标题名称最多不能超过200个字符',
	];

	public function tableData($post)
	{
		if (isset($post['limit'])) {
			$limit = $post['limit'];
		} else {
			$limit = config('paginate.list_rows');
		}
		$tableWhere = $this->tableWhere($post);
		$list = $this->field('*')->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
		foreach ($list as $key => $val) {
			$list[$key]['pic'] = _sImage($val['pic']);
			$list[$key]['ctime'] = getTime($val['ctime']);
			$list[$key]['utime'] = getTime($val['utime']);
		}
		$data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
		$re['code'] = 0;
		$re['msg'] = '';
		$re['count'] = $list->total();
		$re['data'] = $data;
		return $re;
	}

	public function addData($data)
	{
		$validate = new Validate($this->rule, $this->msg);
		$result = [
			'status' => true,
			'msg'    => '保存成功',
			'data'   => ''
		];
		if (! $validate->check($data)) {
			$result['status'] = false;
			$result['msg'] = $validate->getError();
		} else {
			if (! $this->allowField(true)->save($data)) {
				$result['status'] = false;
				$result['msg'] = error_code(10004, true);
			}
		}
		return $result;
	}

	public function saveData($data)
	{
		$validate = new Validate($this->rule, $this->msg);
		$result = [
			'status' => true,
			'msg'    => '保存成功',
			'data'   => ''
		];
		if (! $validate->check($data)) {
			$result['status'] = false;
			$result['msg'] = $validate->getError();
		} else {
			if (! $this->allowField(true)->save($data, ['id' => $data['id']])) {
				$result['status'] = false;
				$result['msg'] = error_code(10004, true);
			}
		}
		return $result;
	}

	protected function tableWhere($post)
	{
		$where = [];
		if (isset($post['title']) && $post['title'] != "") {
			$where[] = [
				'title',
				'like',
				'%' . $post['title'] . '%'
			];
		}
		if (isset($post['utime']) && $post['utime'] != "") {
			$date_array = explode('到', $post['utime']);
			$sutime = strtotime($date_array[0] . '00:00:00', time());
			$eutime = strtotime($date_array[1] . '23:59:59', time());
			$where[] = [
				'utime',
				[
					'EGT',
					$sutime
				],
				[
					'ELT',
					$eutime
				],
				'and'
			];
		}
		$result['where'] = $where;
		$result['field'] = "*";
		$result['order'] = ['id' => 'DESC'];
		return $result;
	}
}